package com.hup.utils.io.socket.udp;

import lombok.extern.log4j.Log4j2;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * @author hugan
 * @date 2020/3/29
 */
@Log4j2
public class DupDataReceiver {

    /**
     * 缓冲大小
     */
    private static final int DEF_BUFFER_SIZE = 1024;

    private byte[] inputBuff;
    private DatagramPacket inputPacket;

    public DupDataReceiver() {
        this(DEF_BUFFER_SIZE);
    }

    public DupDataReceiver(int buffSize) {
        inputBuff = new byte[buffSize];
        inputPacket = new DatagramPacket(inputBuff, inputBuff.length);
    }

    /**
     * @return null-读到数据长度是0;notNull-读取到的数据包
     */
    public UdpData receive(DatagramSocket socket) throws IOException {
        inputPacket.setData(inputBuff);
        socket.receive(inputPacket);
        int readLength = inputPacket.getLength();
        if (readLength <= 0) {
            //对方发送空字符串时就会这样
            log.debug("receive len==0");
            return new UdpData(new byte[0], inputPacket.getAddress(), inputPacket.getPort());
        } else {
            byte[] data = new byte[readLength];
            System.arraycopy(inputBuff, 0, data, 0, readLength);
            return new UdpData(data, inputPacket.getAddress(), inputPacket.getPort());
        }
    }

}
